﻿using Manon.Autofac;
using Manon.ConfigCenter.Web.ApplicationCore.Dtos.User;
using Manon.ConfigCenter.Web.ApplicationCore.Entities;
using Manon.ConfigCenter.Web.ApplicationCore.Interfaces;
using Manon.ConfigCenter.Web.Common;
using Manon.Core.Commons;
using Manon.Core.Extensions;
using Manon.Repository;
using Manon.Repository.Collections;
using Manon.User.Api.ApplicationCore.Entities;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Manon.ConfigCenter.Web.ApplicationCore.Services
{
    public class UserService : IUserService, ISingletonDependency
    {

        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<Result<UserOutput>> ValidateUser(UserLoginInput Input)
        {
            var logger = Resolver.Resolve<ILogger<UserService>>();
            try
            {
                var unitOfWork = Resolver.Resolve<IUnitOfWork<ConfigCenterDbContext>>();


                var result = await unitOfWork.GetRepository<Users>().GetFirstOrDefaultAsync(n => n.UserName == Input.UserName);
                if (result == null)
                {
                    return Result<UserOutput>.Failed("该用户不存在");
                }
                if (MD5Helper.MD5Encrypt(Input.Password) != result.Password)
                {
                    return Result<UserOutput>.Failed("密码不正确");
                }
                if (!result.Enabled)
                {
                    return Result<UserOutput>.Failed("该用户已被禁用");
                }

                return Result<UserOutput>.Successed("验证通过", new UserOutput()
                {
                    Enabled = result.Enabled,
                    RealName = result.RealName,
                    Id = result.Id,
                    UserName = result.UserName
                }); ;
            }
            catch (Exception ex)
            {
                logger.LogError("登录验证异常", ex);
                throw;
            }
        }


        /// <summary>
        /// 获取用户分页列表
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<IPagedList<UserOutput>> GetUserPageList(GetUserPageListInput Input)
        {
            var logger = Resolver.Resolve<ILogger<UserService>>();
            try
            {
                List<UserOutput> list = new List<UserOutput>();

                var unitOfWork = Resolver.Resolve<IUnitOfWork<ConfigCenterDbContext>>();

                Expression<Func<Users, bool>> predicate = null;
                if (!string.IsNullOrEmpty(Input.UserName))
                {
                    predicate = e => e.UserName.Contains(Input.UserName) || e.RealName.Contains(Input.UserName);
                }
                if (Input.Enabled.HasValue)
                {
                    predicate = e => e.Enabled == Input.Enabled.Value;
                }
                var result = await unitOfWork.GetRepository<Users>().GetPagedListAsync<UserOutput>(predicate, Input);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError("获取用户分页列表异常", ex);
                throw;
            }
        }


        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<UserOutput> GetUserById(int UserId)
        {
            if (UserId == 0) return new UserOutput() { Enabled = true };

            var logger = Resolver.Resolve<ILogger<UserService>>();
            try
            {


                var unitOfWork = Resolver.Resolve<IUnitOfWork<ConfigCenterDbContext>>();

                var result = await unitOfWork.GetRepository<Users>().FindAsync(UserId);
                return new UserOutput()
                {

                    CreateTime = result.CreateTime,
                    Enabled = result.Enabled,
                    Id = result.Id,
                    LastLoginTime = result.LastLoginTime,
                    RealName = result.RealName,
                    UpdateTime = result.UpdateTime,
                    UserName = result.UserName
                };
            }
            catch (Exception ex)
            {
                logger.LogError("获取用户信息异常", ex);
                throw;
            }
        }


        public async Task<Result> SaveUser(SaveUserInput Input)
        {
            var logger = Resolver.Resolve<ILogger<UserService>>();
            try
            {
                var identityUser = Resolver.Resolve<IIdentityUser>();
                var unitOfWork = Resolver.Resolve<IUnitOfWork<ConfigCenterDbContext>>();
                var repos = unitOfWork.GetRepository<Users>();

                var existsUser = await repos.ExistsAsync(n => n.Id != Input.Id && n.UserName.Contains(Input.UserName));
                if (existsUser) return Result.Failed("该用户已经存在!");

                var result = await repos.FindAsync(Input.Id);
                if (result == null)
                {
                    result = new Users();
                    result.CreateTime = DateTime.Now;
                    result.Enabled = true;
                    result.Password = MD5Helper.MD5Encrypt(Input.Password);
                    result.RealName = Input.RealName;
                    result.UpdateTime = DateTime.Now;
                    result.UserName = Input.UserName;
                    result.CreateBy = identityUser.UserId;
                    result.UpdateBy = identityUser.UserId;
                    await repos.InsertAsync(result);
                }
                else
                {
                    result.Enabled = Input.Enabled;
                    if (!string.IsNullOrEmpty(Input.Password))
                    {
                        result.Password = MD5Helper.MD5Encrypt(Input.Password);
                    }
                    result.RealName = Input.RealName;
                    result.UpdateTime = DateTime.Now;
                    result.UserName = Input.UserName;
                    result.UpdateBy = identityUser.UserId;
                    repos.Update(result);
                }
                await unitOfWork.SaveChangesAsync();
                return Result.Successed("保存成功!");
            }
            catch (Exception ex)
            {
                logger.LogError("获取用户信息异常", ex);
                throw;
            }
        }


        /// <summary>
        /// 设置用户是否可用
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<Result> SetEnabled(SetUserEnabledInput Input)
        {
            var logger = Resolver.Resolve<ILogger<UserService>>();
            try
            {

                var unitOfWork = Resolver.Resolve<IUnitOfWork<ConfigCenterDbContext>>();

                var user = await unitOfWork.GetRepository<Users>().FindAsync(Input.UserId);
                if (user == null) return null;
                user.Enabled = Input.Enabled;
                await unitOfWork.SaveChangesAsync();
                return Result.Successed("设置成功!");

            }
            catch (Exception ex)
            {
                logger.LogError("设置用户是否可用异常", ex);
                throw;
            }
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<Result> ModifyPassword(ModifyPasswordInput Input)
        {
            var logger = Resolver.Resolve<ILogger<UserService>>();
            try
            {
                if (string.IsNullOrEmpty(Input.Password)) return Result.Failed("请输入原密码");
                if ( string.IsNullOrEmpty(Input.NewPassword)) return Result.Failed("请输入新密码");

                var identityUser = Resolver.Resolve<IIdentityUser>();

                int CurrentUserId = identityUser.UserId;
                var unitOfWork = Resolver.Resolve<IUnitOfWork<ConfigCenterDbContext>>(); 
                var user = await unitOfWork.GetRepository<Users>().FindAsync(CurrentUserId);
                if (user == null) return Result.Failed("该用户不存在");

                if (user.Password != MD5Helper.MD5Encrypt(Input.Password))
                {
                    return Result.Failed("原密码不正确!");
                }

                if (Input.NewPassword != Input.ComfirmNewPassword) {
                    return Result.Failed("新密码与确认密码不一致!");
                }
                user.Password = MD5Helper.MD5Encrypt(Input.NewPassword);
                await unitOfWork.SaveChangesAsync();
                return Result.Successed("密码修改成功!");

            }
            catch (Exception ex)
            {
                logger.LogError("重置密码异常", ex);
                throw;
            }
        }

    }
}
